package com.gensdai.leliang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.serve.ActionEnter;
import com.gensdai.leliang.utils.BaseUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.HttpUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/26.
 */

public class user_enter extends BaseActivityNoAbs implements View.OnClickListener {
    @BindView(R.id.quick_login)
    TextView quick_login;//快速注册
    @BindView(R.id.enter)
    TextView enter; // 登录
    @BindView(R.id.forget_mm)
    TextView forget_mm; // 忘记密码
    @BindView(R.id.phone)
    EditText phone;// 帐号
    @BindView(R.id.mm)
    EditText mm;// 密码
    Unbinder unbinder;
    @BindView(R.id.qq)// QQ
            ImageView qq;
    @BindView(R.id.wx) // 微信
            ImageView wx;
//    @BindView(R.id.back)
//    LinearLayout back;// 后退

    private String QQ_APP_ID = "1106232764";
    private String WX_APP_ID = "wx701d441207f210af";
    private String SCOPE = "all"; //获取信息的范围参数
    private Tencent mTencent; //qq主操作对象
    private IUiListener loginListener; //授权登录监听器
    private IUiListener userInfoListener; //获取用户信息监听器
    private UserInfo userInfo; //qq用户信息
    private IWXAPI api;
    private String openID = "";
    private String accessToken;
    private String expires;

    private boolean tiaozhuan = true;
    private Upload up;
    UserNameBean user;
    SharedPreferences share;
    SharedPreferences.Editor ed;

    private final int ENTER = 1;// 登录标识
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {

                            user = (UserNameBean) new json_base().jsonEnter(new JSONObject((String) msg.obj));
                            ed.putString("waitComment", user.getWaitComment());

                            ActionEnter.saveInfo(user);
//                            ed.putString("user_id", user.getUid());
//                            ed.putString("token", user.getToken());
//                            ed.putBoolean("enter_state", true);
//                            ed.putString("id", user.getId());
//                            ed.putString("user_name", user.getName());
//                            ed.putString("phone", user.getPhone());
//                            ed.putBoolean("hasPayPassword", user.getHasPayPassword());
//                            ed.putString("money", user.getMoney());
//                            ed.putString("recommendUserNo", user.getInviteNumber());
//                            ed.putBoolean("enter_state", true);
//                            ed.putString("memberType", user.getMemberType());
//                            ed.putString("userno", user.getUserno());
//                            ed.putString("daifuNum", user.getDaifuNum());
//                            ed.putString("daifaNum", user.getDaifaNum());
//                            ed.putString("daishouNum", user.getDaishouNum());
//                            ed.putString("name", user.getAddress().getUser_name());
//                            ed.putString("province", user.getAddress().getCityId());
//                            ed.putString("addressId", user.getAddress().getId());
//                            ed.putString("detailAddress", user.getAddress().getAddress());
//                            ed.putString("adressPhone", user.getAddress().getPhone());

                            ed.putString("password", mm.getText().toString().trim());  //用户密码
                            ed.putString("QQopenid", openID);  //QQ标识

                            ed.commit();
                            user_enter.this.finish();
                        } else if (new JSONObject((String) msg.obj)
                                .getString("message").equals("请先绑定第三方账号") && tiaozhuan) {
                            tiaozhuan = false;
                            mTencent.setOpenId(openID);
                            mTencent.setAccessToken(accessToken, expires);
                            System.out.println("开始获取用户信息");
                            userInfo = new UserInfo(user_enter.this, mTencent.getQQToken());
                            userInfo.getUserInfo(userInfoListener);
                        }
                        Toast.makeText(
                                user_enter.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_enter);
        unbinder = ButterKnife.bind(this);
        init();
        initQqLogin();
        initWX();
        setonclick();
    }

    /**
     * 初始化
     */
    private void init() {
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        String ph = share.getString("phone", "");
        String paw = share.getString("password", "");

        if (!ph.equals("")) {
            phone.setText(ph);
            mm.setText(paw);
        }
    }

    private void setonclick() {
        up = new Upload(this);
        quick_login.setOnClickListener(this);
        forget_mm.setOnClickListener(this);
        enter.setOnClickListener(this);
        qq.setOnClickListener(this);
        wx.setOnClickListener(this);
//        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.quick_login:
                Intent go_login = new Intent(this, com.gensdai.leliang.activity.quick_login.class);
                startActivity(go_login);
                break;
            case R.id.enter:
                String name = phone.getText().toString().trim();
                String password = mm.getText().toString().trim();
                if (name.length() < 4) {
                    Toast.makeText(user_enter.this, getResources().getString(R.string.account_mm_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.length() < 6) {
                    Toast.makeText(user_enter.this, "密码不得小于六位，请及时修改!~", Toast.LENGTH_SHORT).show();
//                    return;
                }
                LoginRequest2Str();
                break;
            case R.id.forget_mm:
//                Toast.makeText(this, "功能正在开发中，尽请关注哦！~", Toast.LENGTH_SHORT).show();
                Intent go_set_mm = new Intent(user_enter.this, forget_mm.class);
                go_set_mm.putExtra("title", getString(R.string.forget_mm));
                startActivity(go_set_mm);
                break;
            case R.id.back:
                user_enter.this.finish();
                break;
            case R.id.qq:
//                initQqLogin();
                mTencent.login(this, SCOPE, loginListener);
//                getUserInfoInThread();
                break;
            case R.id.wx:
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                api.sendReq(req);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//  官方文档上面的是错误的
//        if(requestCode == Constants.REQUEST_API) {
//            if(resultCode == Constants.RESULT_LOGIN) {
//                mTencent.handleLoginData(data, loginListener);
//            }
//  resultCode 是log出来的，官方文档里给的那个属性是没有的

        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
            }
        }
    }

    //初始化微信，获取实例
    private void initWX() {
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.registerApp(WX_APP_ID);

    }


    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        mTencent = Tencent.createInstance(QQ_APP_ID, this);
        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object value) {
                //登录成功后回调该方法
//                Toast.makeText(user_enter.this, "登录成功", Toast.LENGTH_SHORT).show();
                System.out.println("有数据返回..");
                if (value == null) {
                    return;
                }

                try {
                    JSONObject jo = (JSONObject) value;

                    int ret = jo.getInt("ret");

//                    System.out.println("json=" + String.valueOf(jo));

                    if (ret == 0) {
//                        Toast.makeText(user_enter.this, "登录成功",
//                                Toast.LENGTH_SHORT).show();

                        openID = jo.getString("openid");
                        accessToken = jo.getString("access_token");
                        expires = jo.getString("expires_in");

                        Map<String, String> loginParams = new HashMap<>();
                        loginParams.put("qqId", openID);   //QQ标识
                        Log.e("QQ标识：", openID);
                        toStr(loginParams);

                    }

                } catch (
                        Exception e)

                {
                    // TODO: handle exception
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(user_enter.this, "登录失败", Toast.LENGTH_SHORT).show();
                Log.e("LoginError:", uiError.toString());
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(user_enter.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        }

        ;

        userInfoListener = new

                IUiListener() {

                    @Override
                    public void onError(UiError arg0) {
                        // TODO Auto-generated method stub
                        Log.e("arg0.toString()：失败s", arg0.toString());
                        Toast.makeText(user_enter.this, "授权失败!",
                                Toast.LENGTH_SHORT).show();
                    }

                    /**
                     * 返回用户信息样例
                     *
                     * {"is_yellow_year_vip":"0","ret":0,
                     * "figureurl_qq_1":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/40",
                     * "figureurl_qq_2":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
                     * "nickname":"攀爬←蜗牛","yellow_vip_level":"0","is_lost":0,"msg":"",
                     * "city":"黄冈","
                     * figureurl_1":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/50",
                     * "vip":"0","level":"0",
                     * "figureurl_2":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
                     * "province":"湖北",
                     * "is_yellow_vip":"0","gender":"男",
                     * "figureurl":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/30"}
                     */
                    @Override
                    public void onComplete(Object arg0) {
                        // TODO Auto-generated method stub
                        if (arg0 == null) {
                            return;
                        }
//                Log.e("arg0.toString():成功",arg0.toString());
                        try {
                            JSONObject jo = (JSONObject) arg0;
                            int ret = jo.getInt("ret");
                            System.out.println("json=" + String.valueOf(jo));
                            String nickName = jo.getString("nickname"); //昵称
                            String gender = jo.getString("gender"); //性别
                            String img = jo.getString("figureurl_qq_2"); //头像
                            Toast.makeText(user_enter.this, "你好，" + nickName,
                                    Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(user_enter.this, NewUser.class);
                            intent.putExtra("type", "亲爱的QQ用户：" + nickName);
                            intent.putExtra("url", img);
                            intent.putExtra("QQopenid", openID);
                            user_enter.this.startActivity(intent);
                            user_enter.this.finish();
                        } catch (Exception e) {
                            // TODO: handle exception
                        }


                    }

                    @Override
                    public void onCancel() {
                        // TODO Auto-generated method stub
                        Toast.makeText(user_enter.this, "取消授权!",
                                Toast.LENGTH_SHORT).show();
                    }
                }

        ;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (share.getBoolean("enter_state", false)) {
            Log.e("登录状态：", "登录");
            this.finish();
        } else {
            Log.e("登录状态：", "未登录");
        }
    }

    /**
     * 调用登陆接口
     */
    private void LoginRequest2Str() {
        //获取edit的值后请求

        String name = phone.getText().toString().trim();
        String password = mm.getText().toString().trim();

        if (TextUtils.isEmpty(password)) {
            return;
        }

        String resultPassword = BaseUtils.EncryptedPassword(password);
        Log.e("password", resultPassword);

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("username", /*"123456"*/name);   //手机号
        loginParams.put("password", resultPassword);                  //密码
        if (getIntent().hasExtra("QQopenid")) {
            loginParams.put("qqId", getIntent().getStringExtra("QQopenid"));   //QQ标识
            Log.e("QQ标识：", getIntent().getStringExtra("QQopenid"));
        }
        if (getIntent().hasExtra("WXopenid")) {
            loginParams.put("unionId", getIntent().getStringExtra("WXopenid")); //微信标识
            Log.e("微信标识：", getIntent().getStringExtra("WXopenid"));
        }
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).LoginRequest2Str(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }
}
